package com.geline.uploadfile;

import com.geline.uploadfile.enums.FileServerEnum;
import com.geline.uploadfile.pojo.JobUploadFileProperties;
import com.geline.uploadfile.pojo.UploadResult;
import com.geline.uploadfile.service.BaseUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 文件上传操作 Service
 * @author: mengxin
 * @date: 2022/11/14 17:53
 */
@Slf4j
public class JobUploadFileService {

    private JobUploadFileProperties properties;
    private BaseUploadService baseUploadService;

    public JobUploadFileService(JobUploadFileProperties properties, BaseUploadService service){
        this.properties = properties;
        this.baseUploadService = service;
    }

    /**
     * 上传文件
     * @param table
     * @param multipartFile
     * @param dirName
     * @param tenantId
     * @return
     */
    public UploadResult uploadFile(String table, MultipartFile multipartFile, String dirName, String tenantId) {
        FileServerEnum serverEnum = properties.getSysFileServer(table);
        UploadResult uploadResult = null;
        if(serverEnum.getIsEcs()){
            uploadResult = baseUploadService.uploadByRemote(tenantId, multipartFile, dirName);
        }else {
            uploadResult = baseUploadService.uploadByLocal(tenantId, multipartFile, dirName);
        }
        return uploadResult;
    }

    public UploadResult uploadFile(String table, String filename, InputStream inputStream, String dirName, String tenantId) {
        FileServerEnum serverEnum = properties.getSysFileServer(table);
        UploadResult uploadResult = null;
        if(serverEnum.getIsEcs()){
            uploadResult = baseUploadService.uploadByRemote(tenantId, filename, inputStream, dirName);
        }else {
            uploadResult = baseUploadService.uploadByLocal(tenantId, filename, inputStream, dirName);
        }
        return uploadResult;
    }

    /**
     * 获取文件流
     * @param serverEnum
     * @param bucket
     * @param objectName
     * @return
     */
    public InputStream getFileInputStream(FileServerEnum serverEnum, String bucket, String objectName) {
        if(serverEnum.getIsEcs()){
            return baseUploadService.getFileByRemote(bucket, objectName);
        }else {
            return baseUploadService.getFileByLocal(bucket, objectName);
        }
    }

    /**
     * 删除文件
     * @param serverEnum
     * @param bucket
     * @param objectName
     * @return
     */
    public boolean deleteFile(FileServerEnum serverEnum, String bucket, String objectName) {
        if(serverEnum.getIsEcs()){
            return baseUploadService.deleteFileByRemote(bucket, objectName);
        }else {
            return baseUploadService.deleteFileByLocal(bucket, objectName);
        }
    }
}
